<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\store\model;

use think\Db;
use think\Model;

class StoreModel extends Model
{
    /**
     * 关联 user表
     * @return $this
     */
    public function user()
    {
        return $this->belongsTo('UserModel', 'user_id')->setEagerlyType(1);
    }
    public function tjuser()
    {
        return $this->belongsTo('UserModel', 'rec_user_id')->setEagerlyType(1);
    }

    function store_list($filter=null,$flag=true,$user_id=0){

        return $this->adminStoreList($filter, true,$flag,$user_id);
    }

    /**
     * @param $filter
     * @param bool $isPage
     * @return \think\Paginator
     * @throws \think\exception\DbException获取店铺列表
     */
    function adminStoreList($filter,$isPage = false,$flag,$user_id){
        $store=new StoreModel();
        $join = [
            ['__USER__ u', 'a.user_id = u.id']
        ];

        $where = [
            'a.store_time' => ['>=', 0],
            'a.delete_time' => 0
        ];
        if($user_id>0){
            $where[ 'a.user_id'] = $user_id;
        }
        if($flag){
            $field = 'a.*,u.user_login,u.user_nickname,u.user_email';
        }else{
            $field = 'a.store_name,a.id,a.address';
        }

        $order='id desc';
        $keyword = empty($filter['keyword']) ? '' : $filter['keyword'];
        if(isset($filter['lat'])&&isset($filter['lng'])){
            $lat=$filter['lat'];
            $lng=$filter['lng'];
            $field=$field.',(ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$lat.'*PI()/180-a.lat*PI()/180)/2),2)+COS('.$lat.'*PI()/180)*COS(a.lat*PI()/180)*POW(SIN(('.$lng.'*PI()/180-a.lng*PI()/180)/2),2)))*1000))/1000 AS juli';
            $order='juli ASC';
            $where[ 'a.status'] = 1;
        }
        if (!empty($keyword)) {
            $where['a.store_name'] = ['like', "%$keyword%"];
        }
        if($isPage){
            $store_list= $store->alias('a')->field($field)
                ->join($join)
                ->where($where)
                ->order($order)
                ->paginate(10);
        }else{
            $store_list= $store->alias('a')->field($field)
                ->join($join)
                ->where($where)
                ->order($order)
                ->select();
        }

        return $store_list;
    }

    /**
     * 添加、编辑店铺
     */
    function add_store($post){
        if (!empty($post['more']['thumbnail'])) {
            $post['more']['thumbnail'] = cmf_asset_relative_url($post['more']['thumbnail']);
        }
        $post['more']=json_encode( $post['more']);
        if(isset($post['id'])){
            $this->allowField(true)->isUpdate(true)->data($post, true)->save();
        }else{
            $post['store_time']=time();
            $this->allowField(true)->data($post, true)->save();
        }
        return $this;
    }


    /**
     * 获取店铺信息
     */
    function get_store_info($id,$stauts=null){
        $where['status']=1;
        $where['delete_time']=0;
        if($stauts){
            $store_info=$this->where($where)->with('user')->with('tjuser')->find($id);
        }else{
            $store_info=$this->with('user')->with('tjuser')->find($id);                
        }
        if($store_info){
            $store_info['more']=json_decode($store_info['more'],true);
            return $store_info;
        }else{
            return null;
        }

    }

    public function adminDeleteStore($data)
    {

        if (isset($data['id'])) {
            $id = $data['id']; //获取删除id
            $res = $this->where(['id' => $id])->find();
            if ($res) {
                $res = json_decode(json_encode($res), true); //转换为数组
                $recycleData = [
                    'object_id'   => $res['id'],
                    'create_time' => time(),
                    'table_name'  => 'store',
                    'name'        => $res['store_name'],
                ];
                Db::startTrans(); //开启事务
                $transStatus = false;
                try {
                    Db::name('store')->where(['id' => $id])->update([
                        'delete_time' => time()
                    ]);
                    Db::name('recycle_bin')->insert($recycleData);

                    $transStatus = true;
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                }
                return $transStatus;
            } else {
                return false;
            }
        } elseif (isset($data['ids'])) {
            $ids = $data['ids'];
            $res = $this->where(['id' => ['in', $ids]])->select();
            if ($res) {
                $res = json_decode(json_encode($res), true);
                foreach ($res as $key => $value) {
                    $recycleData[$key]['object_id']   = $value['id'];
                    $recycleData[$key]['create_time'] = time();
                    $recycleData[$key]['table_name']  = 'store';
                    $recycleData[$key]['name']        = $value['store_name'];
                }
                Db::startTrans(); //开启事务
                $transStatus = false;
                try {
                    Db::name('store')->where(['id' => ['in', $ids]])
                        ->update([
                            'delete_time' => time()
                        ]);
                    Db::name('recycle_bin')->insertAll($recycleData);
                    $transStatus = true;
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                }
                return $transStatus;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
    //获取店铺配卡信息
    function get_card($store_id){
        $res=Db::name('card')->where('store_id',$store_id)->select()->toArray();
        return $res;
    }
    //店铺配卡
    function edit_card($parm){
        //调整状态
        $store['seven_days_card']=$parm['seven_days_card'];
        $store['monthly_card']=$parm['monthly_card'];
        $store['half_year_card']=$parm['half_year_card'];
        $store['year_card']=$parm['year_card'];
        $store['id']=$parm['id'];
        $rs=$this->update($store);
        //七天卡
        $seven['store_id']=$parm['id'];
        $seven['type']=1;
        $seven_res=Db::name('card')->where($seven)->find();

        if($seven_res){
            $seven_up['card_id']=$seven_res['card_id'];
            $seven_up['card_info']=$parm['seven_content'];
            $seven_up['price']=$parm['seven_price'];
            $seven_up['score']=$parm['seven_score'];
            Db::name('card')->update($seven_up);
        }else{
            $seven['card_info']=$parm['seven_content'];
            $seven['price']=$parm['seven_price'];
            $seven['score']=$parm['seven_score'];
            Db::name('card')->insert($seven);
        }

        //月卡
        $monthly['store_id']=$parm['id'];
        $monthly['type']=2;
        $monthly_res=Db::name('card')->where($monthly)->find();
        if($monthly_res){
            $monthly_up['card_id']=$monthly_res['card_id'];
            $monthly_up['card_info']=$parm['monthly_content'];
            $monthly_up['price']=$parm['monthly_price'];
            $monthly_up['score']=$parm['monthly_score'];
            Db::name('card')->update($monthly_up);
        }else{
            $monthly['card_info']=$parm['monthly_content'];
            $monthly['price']=$parm['monthly_price'];
            $monthly['score']=$parm['monthly_score'];
            Db::name('card')->insert($monthly);
        }

        //半年卡
        $half_year['store_id']=$parm['id'];
        $half_year['type']=3;
        $half_year_res=Db::name('card')->where($half_year)->find();
        if($half_year_res){
            $half_year_up['card_id']=$half_year_res['card_id'];
            $half_year_up['card_info']=$parm['half_year_content'];
            $half_year_up['price']=$parm['half_year_price'];
            $half_year_up['score']=$parm['half_year_score'];
            Db::name('card')->update($half_year_up);
        }else{
            $half_year['card_info']=$parm['half_year_content'];
            $half_year['price']=$parm['half_year_price'];
            $half_year['score']=$parm['half_year_score'];
            Db::name('card')->insert($half_year);
        }

        //年卡
        $year['store_id']=$parm['id'];
        $year['type']=4;
        $year_res=Db::name('card')->where($year)->find();
        if($year_res){
            $year_up['card_id']=$year_res['card_id'];
            $year_up['card_info']=$parm['year_content'];
            $year_up['price']=$parm['year_price'];
            $year_up['score']=$parm['year_score'];
            Db::name('card')->update($year_up);
        }else{
            $year['card_info']=$parm['year_content'];
            $year['price']=$parm['year_price'];
            $year['score']=$parm['year_score'];
            Db::name('card')->insert($year);
        }
    }


  /**
     * 获取推荐店铺
     */
        function get_tj_list($id,$type=0){
            $where['delete_time']=0;
            if($type==0){
              $store_info=$this->where('id',$id)->find();
                $tj_store=$this->where('rec_user_id',$store_info['user_id'])->where($where)->paginate(10);
            }
            if($type==1){
              $store_info=$this->where('id',$id)->find();
                $tj_store=$this->where('rec_user_id',$store_info['user_id'])->where($where)->count();
            }
			if($type==2){
                $tj_store=$this->where('id','in',$id)->where($where)->paginate(10);
            }
            if($type==3){
                $tj_store=$this->where('id','in',$id)->where($where)->select();
            }
            return $tj_store;
        }
}